package org.example.mallweb.mallservice.service.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.mallcommon.projo.Carts;
import org.example.mallcommon.result.ReturnResult;
import org.example.mallcommon.vo.CartsVo;
import org.example.mallweb.mallservice.mybatiscommon.carts.CartsMapper;
import org.example.mallweb.mallservice.service.CartsService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 韩先楚
 * 购物车服务实现类
 */
@Service
public class CartsServiceImpl implements CartsService {

    @Resource
    private CartsMapper cartsMapper;

    /**
     * 获取购物车列表
     */
    @Override
    public ReturnResult<List<CartsVo>> list(Integer userId) {
      List<CartsVo> cartsVoList = cartsMapper.list(userId);
      return ReturnResult.success(cartsVoList);
    }

    /**
     * 新增购物车
     * @param carts
     * @return
     */
    @Override
    public ReturnResult<String> add(Carts carts) {
        //查询是否有此商品
        Carts carts1 = cartsMapper.selectOne(new QueryWrapper<Carts>().eq("user_id", carts.getUserId()).eq("product_id", carts.getProductId()));
        if (carts1 == null) {
            cartsMapper.insert(carts);
            return ReturnResult.success("添加成功");
        }
        //如果有此商品，则更新数量
        carts1.setQuantity(carts.getQuantity() + carts1.getQuantity());
        carts1.setPrice(carts.getPrice().add(carts1.getPrice()));
        carts1.setUpdateTime(new Date());
        cartsMapper.updateById(carts1);
        return ReturnResult.success("添加成功");
    }

    /**
     * 删除购物车
     */
    @Override
    public ReturnResult<String> delete( Integer goodsId) {
        if (ObjectUtil.isNotNull(goodsId))
        cartsMapper.deleteById(goodsId);
        return ReturnResult.success("删除成功");
    }
}
